<template>
	<xn-form-container title="新增调解协议" :width="550" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="生成模版" name="templateName">
				<a-select v-model:value="formData.templateName" placeholder="请选择短信模版">
					<a-select-option
						v-for="option in templateList"
						:key="option.fileName"
						:value="option.fileName"
						:label="option.templateName"
					>
						{{ option.templateName }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="调解员电话" name="mediatorPhone">
				<a-input v-model:value="formData.mediatorPhone" placeholder="请输入调解员电话" allow-clear :maxlength="11" />
			</a-form-item>
			<a-form-item label="收款账户" name="bankCode">
				<a-select
					v-model:value="formData.bankCode"
					mode="multiple"
					placeholder="请选择收款账户"
					:options="bankList"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="被申请人姓名" name="debtorName">
				<a-input v-model:value="formData.debtorName" placeholder="请输入被申请人姓名" allow-clear />
			</a-form-item>
			<a-form-item label="被申请人身份证号" name="debtorCardId">
				<a-input v-model:value="formData.debtorCardId" placeholder="被申请人身份证号" allow-clear />
			</a-form-item>
			<a-form-item label="被申请人性别" name="debtorSex">
				<a-select v-model:value="formData.debtorSex" placeholder="请选择用户标签" :options="sexOptions" allowClear />
			</a-form-item>
			<a-form-item label="欠款人手机号" name="debtorPhone">
				<a-input v-model:value="formData.debtorPhone" placeholder="请输入手机号" allow-clear :maxlength="11" />
			</a-form-item>
			<a-form-item label="合同编号" name="contractNo">
				<a-input v-model:value="formData.contractNo" placeholder="请输入合同编号" allow-clear />
			</a-form-item>
			<a-form-item label="合同开始日期" name="contractStartDate">
				<a-date-picker
					v-model:value="formData.contractStartDate"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					placeholder="请选择日期"
					style="width: 100%"
				/>
			</a-form-item>
			<!-- 金融信息 -->
			<a-form-item label="逾期天数" name="overdueDays">
				<a-input-number
					v-model:value="formData.overdueDays"
					placeholder="请输入逾期天数"
					:min="0"
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="欠款总额" name="overdueAmount">
				<a-input-number
					v-model:value="formData.overdueAmount"
					placeholder="请输入欠款金额"
					:min="0"
					:precision="2"
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="结清金额" name="settlementAmount">
				<a-input-number
					v-model:value="formData.settlementAmount"
					placeholder="请输入欠款金额"
					:min="0"
					:precision="2"
					style="width: 100%"
				/>
			</a-form-item>
			<!-- 动态附加信息 -->
			<a-divider>分期明细</a-divider>
			<div v-for="(item, index) in formData.detailJson" :key="item.key || index">
				<a-space style="display: flex; margin-bottom: 8px" align="baseline">
					<a-form-item :name="['detailJson', index, 'detailAmount']" :rules="userFieldRules.detailAmount">
						<a-input v-model:value="item.detailAmount" placeholder="输入还款金额" />
					</a-form-item>
					<a-form-item :name="['detailJson', index, 'detailDate']" :rules="userFieldRules.detailDate">
						<a-date-picker
							v-model:value="item.detailDate"
							format="YYYY年MM月DD日"
							value-format="YYYY年MM月DD日"
							placeholder="输入还款时间"
							style="width: 120%"
						/>
					</a-form-item>
					<minus-circle-outlined
						v-if="formData.detailJson.length > 1"
						@click="removeDetail(index)"
						style="color: #ff4d4f; cursor: pointer; margin-left: 200%"
					/>
				</a-space>
			</div>
			<a-form-item>
				<a-button type="dashed" @click="addDetail" block>
					<plus-outlined />
					添加分期明细
				</a-button>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { reactive, ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { required } from '@/utils/formRules'
	import wordMediationApi from '@/api/tjzy/word/mediation/wordMediationApi'
	import tool from '@/utils/tool'
	import bankApi from '@/api/tjzy/bank/bankApi'
	import { isBlank } from '@/utils/stringUtil'
	import excelTemplateApi from '@/api/tjzy/excel/template/excelTemplateApi'

	// 组件状态
	const visible = ref(false)
	const submitLoading = ref(false)
	const formRef = ref()
	const emit = defineEmits(['successful'])
	const sexOptions = tool.dictList('Sex')
	const templateList = ref([])
	const bankList = ref([])
	// 表单数据结构
	const formData = ref({
		bankCode: undefined,
		debtorPhone: undefined,
		noSensitiveDebtorPhone: undefined,
		debtorCardId: undefined,
		noSensitiveDebtorCardId: undefined,
		overdueDays: 0,
		overdueAmount: 0,
		settlementAmount: 0,
		detailJson: [
			{
				key: Date.now()
			}
		]
	})

	// 验证规则
	const formRules = reactive({
		templateName: [required('生成模版')],
		mediatorPhone: [required('调解员电话')],
		debtorName: [required('被申请人姓名')],
		debtorCardId: [required('被申请人身份证号')],
		debtorSex: [required('被申请人性别')],
		debtorPhone: [required('手机号')],
		contractNo: [required('合同编号')],
		contractStartDate: [required('合同开始日期')],
		debtorClientId: [required('客户ID')],
		overdueDays: [required('逾期天数')],
		overdueAmount: [required('欠款金额')],
		settlementAmount: [required('结清金额')]
	})

	// 动态字段验证规则
	const userFieldRules = {
		detailAmount: [required('还款金额')],
		detailDate: [required('还款时间')]
	}

	const onOpen = (record) => {
		bankApi.listAll().then((res) => {
			bankList.value = res.map((item) => ({
				value: item.code,
				label: item.name
			}))
		})
		excelTemplateApi.getTemplateListByType(7).then((res) => {
			templateList.value = res
		})
		visible.value = true
		if (record) {
			// 处理动态字段 detailJson
			formData.value = Object.assign(formData.value, record)
			if (record.detailJson) {
				formData.value.detailJson = JSON.parse(record.detailJson).map((item, index) => ({
					...item,
					key: Date.now() + index // 确保每个明细项的 key 唯一
				}))
			} else {
				formData.value.detailJson = [{ detailAmount: '', detailDate: '', key: Date.now() }]
			}
			if (formData.value.bankCode) {
				formData.value.bankCode = record.bankCode.split(',')
			} else {
				formData.value.bankCode = undefined
			}
			if (isBlank(record.mediatorPhone)) {
				formData.value.mediatorPhone = tool.data.get('USER_INFO').phone
			} else {
				formData.value.mediatorPhone = record.mediatorPhone
			}
		} else {
			formData.value.mediatorPhone = tool.data.get('USER_INFO').phone
		}
	}
	// 表单重置
	const onClose = () => {
		formData.value = {
			bankCode: undefined,
			debtorPhone: undefined,
			noSensitiveDebtorPhone: undefined,
			debtorCardId: undefined,
			noSensitiveDebtorCardId: undefined,
			overdueDays: 0,
			overdueAmount: 0,
			settlementAmount: 0,
			detailJson: [
				{
					key: Date.now()
				}
			]
		}
		visible.value = false
	}

	// 字段操作
	const addDetail = () => {
		console.log(formData.value)
		formData.value.detailJson.push({
			detailAmount: '',
			detailDate: '',
			key: Date.now()
		})
	}

	const removeDetail = (index) => {
		if (formData.value.detailJson.length > 1) {
			formData.value.detailJson.splice(index, 1)
		} else {
			message.warning('至少需要保留一条还款明细')
		}
	}

	// 表单提交
	const onSubmit = () => {
		console.log(formData.value)
		formRef.value.validate().then(() => {
			// 处理数据格式
			const payload = {
				...formData.value,
				bankCode: formData.value.bankCode ? formData.value.bankCode.join(',') : undefined,
				debtorPhone: formData.value.debtorPhone.includes('****')
					? formData.value.noSensitiveDebtorPhone
					: formData.value.debtorPhone,
				debtorCardId: formData.value.debtorCardId.includes('****')
					? formData.value.noSensitiveDebtorCardId
					: formData.value.debtorCardId,
				detailJson: JSON.stringify(formData.value.detailJson),
				overdueAmount: Number(formData.value.overdueAmount),
				overdueDays: Number(formData.value.overdueDays)
			}
			submitLoading.value = true
			try {
				wordMediationApi.addOrEdit(payload).then((res) => {
					emit('successful', res)
				})
			} catch (e) {
				submitLoading.value = false
			} finally {
				submitLoading.value = false
				onClose()
			}
		})
	}

	defineExpose({
		onOpen
	})
</script>
